from django.shortcuts import render
from django.http import HttpResponse
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser
from rest_framework import status
from movies.models import Movie
from movies.serializers import MovieSerializers
import json

# Create your views here.
# 继承HttpResponse类，定义一个返回json数据的响应类
class JsonResponse(HttpResponse):
    def __init__(self, data, **kwargs):
        # 重写content属性，返回rest_framework的JSON渲染器渲染的数据
        content = JSONRenderer().render(data)
        # 通过kwargs设置返回的数据类型为json
        kwargs['content_type'] = 'application/json'
        super(JsonResponse, self).__init__(content, **kwargs)

# 电影列表资源
@csrf_exempt
def movie_list(request):
    if request.method == 'GET':
        # 查询所有电影信息
        movies = Movie.objects.order_by("-pk")
        print(type(movies))
        # 实例化一个序列化器，指示为多条数据的序列化
        movies_serializer = MovieSerializers(movies, many=True)
        # print(movies_serializer.data)
        # 返回序列化的json数据
        print(movies_serializer.data)
        return JsonResponse(movies_serializer.data)

    elif request.method == 'POST':
        # 解析http请求的数据
        movie_data = json.loads(request.body)
        # movie_data = JSONParser().parse(request)
        print(movie_data)
        # 实例化一个序列化器
        movies_serializer = MovieSerializers(data=movie_data)
        # 如果序列化数据有效
        if movies_serializer.is_valid():
            movies_serializer.save()
            return JsonResponse(movies_serializer.data, status=status.HTTP_201_CREATED)
        return JsonResponse(movies_serializer.errors, status=status.HTTP_400_BAD_REQUEST)

@csrf_exempt
def movie_detail(request, pk):
    # 首先判断是否存在相关数据
    print(pk)
    try:
        movie = Movie.objects.get(pk=pk)
    except Movie.DoesNotExist as e:
        return HttpResponse(e, status=status.HTTP_404_NOT_FOUND)
    if request.method == 'GET':
        # 获取电影详情资源
        movies_serializer = MovieSerializers(movie)
        return JsonResponse(movies_serializer.data)
    elif request.method == 'PUT':
        # 修改电影详情
        movie_data = JSONParser().parse(request)
        movie_serializers = MovieSerializers(movie, data=movie_data)
        if movie_serializers.is_valid():
            movie_serializers.save()
            return JsonResponse(movie_serializers.data)
        return JsonResponse(movie_serializers.errors, status=status.HTTP_400_BAD_REQUEST)
    elif request.method == 'DELETE':
        # 删除电影信息
        movie.delete()
        reposen = {"code": status.HTTP_200_OK, "msg": "成功"}
        return JsonResponse(reposen)


def open_view(request):
    return render(request, "test001.html")
